package com.example.springboot.security.service;

import com.example.springboot.security.dao.RoleRepository;
import com.example.springboot.security.dao.UserRepository;
import com.example.springboot.security.entity.SysRole;
import com.example.springboot.security.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc:实现security 权限控制类UserDetailsService，实现方法loadUserByUsername
 * @Author wangsh
 * @date 2018/6/14 22:19
 */
public class UserServiceImpl implements UserDetailsService {


	@Autowired
	private UserRepository userRepository;
	@Autowired
	private RoleRepository roleRepository;

	/**
	 * 实现该方法，编写自定义权限
	 *
	 * @param userName
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

		//查询用户
		SysUser user = userRepository.findByUserName(userName);

		//添加权限
		List<GrantedAuthority> aulist = new ArrayList<GrantedAuthority>();
//		aulist.add(new SimpleGrantedAuthority("ROLE_NAME"));
		Iterable<SysRole> sysRoles = roleRepository.findAll();
		for (SysRole role : sysRoles) {
			aulist.add(new SimpleGrantedAuthority(role.getRoleName()));
		}

		org.springframework.security.core.userdetails.User secUser = new org.springframework.security.core.userdetails.User(user.getUserName(),
				user.getPassword(), aulist);

		return secUser;
	}
}
